// ComponentManager.js

class ComponentManager {
    constructor() {
        this.robot = null;
        this.components = null;

        // 订阅状态更新
        window.robotStateManager?.addComponentListener(components => {
            if (components) {
                this.updateComponentsState(components);
            }
        });
    }

    setRobot(robot) {
        this.robot = robot;
        this.components = robot?.components || null;

        // 初始化完成后，立即同步一次状态
        if (this.components && window.robotStateManager) {
            const currentState = window.robotStateManager.getState();
            this.updateComponentsState(currentState.components);
        }
    }

    // 统一的组件状态更新入口
    updateComponentsState(components) {
        if (!components || !this.components) return;

        try {
            // 更新轮子状态
            if (components.motion?.wheels) {
                this.updateWheels(components.motion.wheels);
            }

            // 更新清扫系统状态
            if (components.cleaning) {
                this.updateCleaningSystem(components.cleaning);
            }

            // 更新拖地系统
            if (components.cleaning?.mop) {
                this.updateMoppingSystem(components.cleaning.mop);
            }

            // 更新容器状态
            if (components.containers) {
                this.updateContainers(components.containers);
            }

            // 更新传感器状态
            if (components.sensors) {
                this.updateSensors(components.sensors);
            }

            // 更新按钮状态
            if (components.keyLeds) {
                this.updateButtonStates(components.keyLeds);
            }

            // 更新动画
            this.updateAnimations();
        } catch (error) {
            console.error('Error in updateComponentsState:', error);
            console.debug('Components state:', components);
            console.debug('Current components:', this.components);
        }
    }

    // 轮子相关更新
    updateWheels(wheelStates) {
        if (!wheelStates) return;

        const { left = {}, right = {} } = wheelStates;

        // 更新左轮
        if (left) {
            this.updateWheelVisual(0, left.rotating || false, left.speed || 0, left.offGround || false);
        }

        // 更新右轮
        if (right) {
            this.updateWheelVisual(1, right.rotating || false, right.speed || 0, right.offGround || false);
        }
    }

    updateWheelVisual(wheelIndex, isRotating, speed, isOffGround) {
        if (!this.components?.wheels?.[wheelIndex]) return;

        const wheel = this.components.wheels[wheelIndex];

        // 更新位置
        wheel.position.y = isOffGround ?
            -robotConfig.body.height / 7 - robotConfig.wheels.liftHeight :
            -robotConfig.body.height / 7;

        // 更新颜色
        let color;
        if (isRotating) {
            color = isOffGround ?
                robotConfig.wheels.colorRotateOff :
                robotConfig.wheels.colorRotate;
        } else {
            color = isOffGround ?
                robotConfig.wheels.colorStaticOff :
                robotConfig.wheels.colorStatic;
        }
        wheel.material.color.setHex(color);
    }

    // 动画更新系统
    updateAnimations() {
        const state = window.robotStateManager?.getState()?.components;
        if (!state) return;

        this.updateWheelAnimations(state);
        this.updateBrushAnimations(state);
        this.updateLidarAnimation(state);
        this.updateMopAnimation(state);
        this.updateFanAnimation(state);
    }

    updateWheelAnimations(state) {
        if (state.motion?.wheels) {
            // 左轮动画
            if (state.motion.wheels.left?.rotating && this.components?.wheels[0]) {
                this.components.wheels[0].rotation.x += state.motion.wheels.left.speed || 0;
            }
            // 右轮动画
            if (state.motion.wheels.right?.rotating && this.components?.wheels[1]) {
                this.components.wheels[1].rotation.x += state.motion.wheels.right.speed || 0;
            }
        }
    }

    // 清扫系统更新
    updateCleaningSystem(cleaningState) {
        if (!cleaningState) return;

        const { brush = {}, vacuum = {} } = cleaningState;
        const { side = {}, main = {} } = brush;

        // 更新边刷状态
        if (side) {
            this.updateSideBrushVisual(
                side.enabled || false,
                side.speed || 0
            );
        }

        // 更新主刷状态
        if (main) {
            this.updateMainBrushVisual(
                main.enabled || false,
                main.speed || 0
            );
        }

        // 更新吸尘器状态
        if (vacuum) {
            this.updateFanVisual(
                vacuum.enabled || false,
                vacuum.fanSpeed || 0
            );
        }
    }

    updateSideBrushVisual(isEnabled, speed) {
        if (!this.components?.sideBrushes) return;

        const color = isEnabled ?
            robotConfig.brushes.side.activeColor :
            robotConfig.brushes.side.colorStatic;

        this.components.sideBrushes.children.forEach(arm => {
            if (arm instanceof THREE.Mesh && arm.material) {
                arm.material.color.setHex(color);
            }
        });
    }

    updateMainBrushVisual(isEnabled, speed) {
        if (!this.components?.mainBrush) return;

        this.components.mainBrush.material.color.setHex(
            isEnabled ? robotConfig.brushes.main.activeColor : robotConfig.brushes.main.colorStatic
        );
    }

    updateFanVisual(isEnabled, speed) {
        if (!this.components?.fan) return;

        const emissiveColor = isEnabled ? 0xDF2C00 : 0x000000;
        if (this.components.fan.children[0]?.material) {
            this.components.fan.children[0].material.emissive.setHex(emissiveColor);
        }
        if (this.components.fan.children[2]?.material) {
            this.components.fan.children[2].material.emissive.setHex(emissiveColor);
        }
    }

    updateBrushAnimations(state) {
        // 边刷旋转动画
        if (state.cleaning?.brush?.side?.enabled && this.components?.sideBrushes) {
            this.components.sideBrushes.rotation.y += state.cleaning.brush.side.speed || 0;
        }

        // 主刷旋转动画
        if (state.cleaning?.brush?.main?.enabled && this.components?.mainBrush) {
            this.components.mainBrush.rotation.x += state.cleaning.brush.main.speed || 0;
        }
    }

    updateFanAnimation(state) {
        // 风扇扇叶旋转
        if (state.cleaning?.vacuum?.enabled && this.components?.fan?.bladesGroup) {
            this.components.fan.bladesGroup.rotation.z += state.cleaning.vacuum.fanSpeed || 0;
        }
    }

    // 容器状态更新
    updateContainers(containerStates) {
        if (!containerStates) return;

        const { waterTank = {}, dustbin = {} } = containerStates;

        // 更新水箱状态
        this.updateWaterTankVisual(waterTank.attached || false, waterTank.level || 0);

        // 更新尘盒状态
        this.updateDustbinVisual(dustbin.attached || false, dustbin.full || false);

        // 更新清洁液容器状态
        if (containerStates.cleaningFluid) {
            this.updateCleaningFluidVisual(
                containerStates.cleaningFluid.attached || false,
                containerStates.cleaningFluid.level || 0,
                containerStates.cleaningFluid.type || 'none'
            );
        }

    }

    updateWaterTankVisual(isAttached, waterLevel) {
        if (!this.components?.waterTank) return;

        let color;
        if (isAttached) {
            color = waterLevel ? robotConfig.waterTank.colorWater : robotConfig.waterTank.colorEmpty;
        } else {
            color = robotConfig.waterTank.colorAbsent;
        }

        this.components.waterTank.material.color.setHex(color);
    }

    updateDustbinVisual(isAttached, isFull) {
        if (!this.components?.dustBox) return;

        let color;
        if (isAttached) {
            color = isFull ? robotConfig.dustBox.colorFull : robotConfig.dustBox.colorEmpty;
        } else {
            color = robotConfig.dustBox.colorAbsent;
        }

        this.components.dustBox.material.color.setHex(color);
    }

    // 添加清洁液容器的视觉更新
    updateCleaningFluidVisual(isAttached, level, type) {
        if (!this.components?.cleaningFluid) return;

        const container = this.components.cleaningFluid;

        // 更新容器可见性
        container.visible = isAttached;

        if (isAttached) {
            // 更新液位显示
            if (container.levelIndicator) {
                container.levelIndicator.scale.y = level / 100;
            }

            // 更新颜色基于类型
            const colors = {
                'none': robotConfig.cleaningFluid.colorEmpty,
                'standard': robotConfig.cleaningFluid.colorStandard,
                'strong': robotConfig.cleaningFluid.colorStrong,
                'eco': robotConfig.cleaningFluid.colorEco
            };

            const color = colors[type] || colors.none;
            container.material.color.setHex(color);

            // 更新透明度基于液位
            container.material.opacity = 0.3 + (level / 100) * 0.7;
        }
    }

    // 传感器系统更新
    updateSensors(sensorStates) {
        if (!sensorStates) return;

        try {
            // 相机传感器
            if (sensorStates.camera?.main) {
                this.updateCameraVisual(
                    sensorStates.camera.main.enabled || false,
                    sensorStates.camera.main.fillLight || false
                );
            }

            // 悬崖传感器
            if (sensorStates.cliff) {
                Object.entries(sensorStates.cliff).forEach(([position, isActive], index) => {
                    this.updateCliffSensorVisual(index, isActive);
                });
            }

            // 红外传感器
            if (sensorStates.ir) {
                Object.entries(sensorStates.ir).forEach(([position, isActive], index) => {
                    this.updateIRSensorVisual(index, isActive);
                });
            }

            // 激光雷达
            if (sensorStates.lidar) {
                const rotating = sensorStates.lidar.rotating ?? false;
                const speed = sensorStates.lidar.speed ?? 0;
                this.updateLidarVisual(rotating, speed);

                if (sensorStates.lidar.switches) {
                    this.updateLidarSwitchesVisual(sensorStates.lidar.switches);
                }
            }

            // 前方碰撞传感器
            if (sensorStates.frontBumper && this.components?.bumperGroup) {
                // 左前碰撞
                const leftBumper = this.components.bumperGroup.children[0];
                if (leftBumper?.material) {
                    this.updateBumperState(leftBumper, sensorStates.frontBumper.left);
                }

                // 右前碰撞
                const rightBumper = this.components.bumperGroup.children[1];
                if (rightBumper?.material) {
                    this.updateBumperState(rightBumper, sensorStates.frontBumper.right);
                }
            }

            // TOF传感器
            if (sensorStates.tof) {
                this.updateTofSensorVisual(
                    sensorStates.tof.enabled ?? false,
                    sensorStates.tof.distance ?? 0
                );
            }

            // 线激光
            if (sensorStates.lineLaser) {
                this.updateLineLaserVisual(
                    sensorStates.lineLaser.enabled ?? false
                );
            }
        } catch (error) {
            console.error('Error updating sensors:', error);
        }
    }

    updateCameraVisual(isEnabled, fillLightOn) {
        if (!this.components?.camera?.main) return;

        const camera = this.components.camera.main;

        // 更新相机LED状态
        if (camera.fillLight) {
            camera.fillLight.material.emissiveIntensity = fillLightOn ? 1 : 0;
        }

        // 更新相机状态指示
        if (camera.statusLed) {
            camera.statusLed.material.emissiveIntensity = isEnabled ? 1 : 0;
        }
    }

    updateCliffSensorVisual(index, isActive) {
        if (!this.components?.cliffSensors?.[index]) return;

        const sensor = this.components.cliffSensors[index];
        sensor.material.emissiveIntensity = isActive ? 1 : 0;
    }

    updateIRSensorVisual(index, isActive) {
        if (!this.components?.irSensors?.[index]) return;

        const sensor = this.components.irSensors[index];
        sensor.material.emissiveIntensity = isActive ? 1 : 0;
    }

    updateLidarVisual(isRotating, speed) {
        if (!this.components?.lidar) return;

        // 更新底座颜色
        if (this.components.lidarBase?.material) {
            this.components.lidarBase.material.color.setHex(
                isRotating ? robotConfig.lidar.activeColor : robotConfig.lidar.color
            );
        }

        // 更新激光线可见性
        if (this.components.lidarLaser) {
            this.components.lidarLaser.visible = isRotating;
        }
    }

    updateLidarAnimation(state) {
        // 雷达旋转动画
        if (state.sensors?.lidar?.rotating && this.components?.lidar) {
            const rotationSpeed = state.sensors.lidar.speed || 0;
            this.components.lidar.rotation.y += rotationSpeed;
            if (this.components.lidarLaser) {
                this.components.lidarLaser.rotation.y += rotationSpeed;
            }
        }
    }

    updateLidarSwitchesVisual(switchStates) {
        if (!this.components?.lidarSwitches || typeof switchStates !== 'object') return;

        Object.entries(switchStates).forEach(([position, isActive], index) => {
            if (this.components.lidarSwitches[index]) {
                const newColor = isActive ?
                    robotConfig.lidar.switches.activeColor :
                    robotConfig.lidar.switches.color;
                this.components.lidarSwitches[index].material.color.setHex(newColor);
            }
        });
    }

    updateFrontBumperVisual(leftTriggered, rightTriggered) {
        if (!this.components?.frontBumpers) return;

        // 更新左前碰撞
        if (this.components.frontBumpers.left) {
            const leftBumper = this.components.frontBumpers.left;
            this.updateBumperState(leftBumper, leftTriggered);
        }

        // 更新右前碰撞
        if (this.components.frontBumpers.right) {
            const rightBumper = this.components.frontBumpers.right;
            this.updateBumperState(rightBumper, rightTriggered);
        }
    }

    updateBumperState(bumper, isTriggered) {
        if (!bumper?.material) return;

        // 存储初始状态
        if (!bumper.defaultState) {
            bumper.defaultState = {
                position: bumper.position.clone(),
                color: robotConfig.bumper.colorStatic,
                opacity: robotConfig.bumper.opacity
            };
        }

        // 更新颜色和透明度
        const color = isTriggered ?
            robotConfig.bumper.colorActive :
            robotConfig.bumper.colorStatic;
        const opacity = isTriggered ?
            robotConfig.bumper.activeOpacity :
            robotConfig.bumper.opacity;

        bumper.material.color.setHex(color);
        bumper.material.opacity = opacity;

        //console.log("c:", color, "o:", opacity);

        // 位置动画
        if (isTriggered) {
            const time = Date.now() * 0.005;
            const offset = Math.sin(time) * 0.002;
            bumper.position.z = bumper.defaultState.position.z + offset;
        } else {
            // 恢复默认位置
            bumper.position.copy(bumper.defaultState.position);
        }
    }

    // 碰撞反馈动画
    addBumperFeedbackAnimation(bumper) {
        if (!bumper) return;

        const originalPosition = bumper.position.clone();
        const originalColor = bumper.material.color.getHex();
        const originalOpacity = bumper.material.opacity;

        // 创建动画
        const startTime = Date.now();
        const duration = 200; // 动画持续时间（毫秒）

        const animate = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);

            // 位置偏移动画
            const offset = Math.sin(progress * Math.PI) * 0.002;
            bumper.position.z = originalPosition.z + offset;

            // 颜色过渡动画
            const t = (Math.sin(progress * Math.PI * 2) + 1) / 2;
            const currentColor = robotConfig.sensors.frontBumper.activeColor * t +
                               robotConfig.sensors.frontBumper.normalColor * (1 - t);
            bumper.material.color.setHex(currentColor);

            if (progress < 1) {
                requestAnimationFrame(animate);
            } else {
                // 恢复原始状态
                bumper.position.copy(originalPosition);
                bumper.material.color.setHex(originalColor);
                bumper.material.opacity = originalOpacity;
            }
        };

        requestAnimationFrame(animate);
    }

    updateTofSensorVisual(isEnabled, distance) {
        if (!this.components?.tofSensor) return;

        const sensorMesh = this.components.tofSensor.children[0];
        if (sensorMesh?.material) {
            sensorMesh.material.emissive.setHex(
                isEnabled ? robotConfig.tofSensor.activeColor : 0x000000
            );
        }

        // 更新距离线
        if (this.components.tofSensor.distanceLine) {
            const line = this.components.tofSensor.distanceLine;
            line.visible = isEnabled;

            if (isEnabled && line.geometry?.attributes?.position) {
                const points = line.geometry.attributes.position.array;
                points[5] = -distance;
                line.geometry.attributes.position.needsUpdate = true;
            }
        }
    }

    updateLineLaserVisual(isEnabled) {
        if (!this.components?.lineLaser) return;

        // 更新激光线可见性
        if (this.components.lineLaser.laserLines) {
            this.components.lineLaser.laserLines.forEach(line => {
                if (line) line.visible = isEnabled;
            });
        }

        if (this.components.lineLaser.laserLinesGround) {
            this.components.lineLaser.laserLinesGround.forEach(line => {
                if (line) line.visible = isEnabled;
            });
        }

        // 更新传感器主体状态
        const sensorMesh = this.components.lineLaser.children[0];
        if (sensorMesh?.material) {
            const newColor = isEnabled ?
                robotConfig.lineLaser.activeColor :
                robotConfig.lineLaser.color;
            sensorMesh.material.color.setHex(newColor);
            sensorMesh.material.emissive.setHex(newColor);
        }
    }

    // 拖布系统更新
    updateMoppingSystem(moppingState) {
        if (!this.components?.mop) return;

        try {
            const {
                enabled = false,
                lift = false,
                vibrate = false,
                waterFlow = 0
            } = moppingState;

            // 更新拖布状态
            const baseHeight = -robotConfig.body.height / 2;

            // 更新拖布可见性和位置
            this.components.mop.visible = enabled;
            if (enabled) {
                this.components.mop.position.y = lift ?
                    baseHeight + robotConfig.mop.liftHeight :
                    baseHeight;
            }

            // 更新拖布颜色（基于水量）
            this.updateMopColorByWaterFlow(enabled, waterFlow);

            // 更新振动状态
            if (enabled && vibrate) {
                this.components.mop.vibrationEnabled = true;
                this.components.mop.vibrationIntensity = waterFlow / 100; // 归一化强度
            } else {
                this.components.mop.vibrationEnabled = false;
            }

        } catch (error) {
            console.error('Error updating mopping system:', error);
        }
    }

    updateMopColorByWaterFlow(enabled, waterFlow) {
        if (!this.components?.mop?.material) return;

        let mopColor;
        if (!enabled) {
            mopColor = robotConfig.mop.colorStatic;
        } else {
            // 基于水量级别选择颜色
            const waterLevel = Math.floor(waterFlow / 33); // 将0-100的水量分为3级
            const waterLevelColors = {
                0: robotConfig.mop.colorDry,
                1: robotConfig.mop.colorLowWater,
                2: robotConfig.mop.colorMediumWater,
                3: robotConfig.mop.colorHighWater
            };
            mopColor = waterLevelColors[waterLevel] || robotConfig.mop.colorDry;
        }

        this.components.mop.material.color.setHex(mopColor);
    }

    updateMopAnimation(state) {
        if (!this.components?.mop) return;

        const moppingState = state.cleaning?.mop;
        if (!moppingState?.enabled) return;

        switch(robotConfig.mop.type) {
            case 'rect':
                // 矩形拖布暂无动画
                break;
            case 'semicircle':
                if (moppingState.lift && moppingState.vibrate) {
                    const intensity = moppingState.waterFlow / 1000; // 振动强度与水量相关
                    this.components.mop.position.z +=
                        Math.sin(Date.now() * intensity) * 0.0005;
                }
                break;
            case 'circle':
                if (moppingState.enabled) {
                    const mopAngle = (Date.now() * 0.001) % (Math.PI * 2);
                    this.updateCircularMopPosition(mopAngle);
                }
                break;
        }
    }

    updateCircularMopPosition(angle) {
        if (!this.components?.mop?.pivot) return;

        const radius = robotConfig.mop.moveRadius;
        const x = Math.cos(angle) * radius;
        const z = Math.sin(angle) * radius;
        this.components.mop.pivot.position.set(x, 0, z);
    }

    // 界面元素更新
    updateButtonStates(interfaceState) {
        if (!interfaceState) return;

        // 更新电源按钮
        if (interfaceState.powerButton) {
            this.updateButtonVisual(
                'powerButton',
                interfaceState.powerButton.pressed || false,
                interfaceState.powerButton.ledOn || false
            );
        }

        // 更新充电按钮
        if (interfaceState.homeButton) {
            this.updateButtonVisual(
                'homeButton',
                interfaceState.homeButton.pressed || false,
                interfaceState.homeButton.ledOn || false
            );
        }
    }

    updateButtonVisual(buttonName, isPressed, isLedOn) {
        const button = this.components[buttonName];
        if (!button) return;


        // 更新按键物理状态
        const buttonMesh = button.children[0];
        if (buttonMesh?.material) {
            buttonMesh.material.color.setHex(
                isPressed ? robotConfig.buttons.activeColor : robotConfig.buttons.color
            );
            buttonMesh.position.y = isPressed ? -0.002 : 0; // 按下时略微下沉
        }

        // 更新 LED 状态
        const ledMesh = button.children[1];
        if (ledMesh?.material) {
            ledMesh.material.emissiveIntensity = isLedOn ? 1 : 0;
            ledMesh.material.opacity = isLedOn ? 1 : 0.5;
        }
    }

    // 销毁方法
    destroy() {
        // 清理所有组件状态
        this.components = null;
        this.robot = null;
    }
}

// 创建全局单例
const componentManager = new ComponentManager();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.componentManager = componentManager;
    window.ComponentManager = ComponentManager;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        ComponentManager,
        componentManager
    };
}
